// Check localStorages.
function checkLocalStorageGames(){
	// Check game count.
	if (localStorage.totalGames){
		localStorage.totalGames = parseInt(localStorage.totalGames)+1;
	} else {
		localStorage.totalGames = 1;
	}
	// Save games to localStorage.
	localStorage["game"+parseInt(localStorage.totalGames)] = game;
	localStorage["shipsPlayer"+parseInt(localStorage.totalGames)] = shipsPlayer;
}

// Deploy user ships on the field for replay.
function deployUserShips(){
	for (var i = 0; i < shipsPlayer.length; i++){
		document.getElementById(game[replayIndex]).style.background = deployedShip;
	}	
}

// Play the replay.
function replay(){
	if (replayIndex >= game.length){
		replayIndex = 0;
		isTableClear = true;
		clearTable();
		game = stringToIntArray(gameToReplay);
		shipsPlayer = stringToIntArray(latestUserDeploy);
		deployUserShips();		
	}
	
	if (game.length == 0){
		game = stringToIntArray(gameToReplay);
		shipsPlayer = stringToIntArray(latestUserDeploy);
		deployUserShips();
		
	}
	// Check if table is clear.
	if (!isTableClear){
		isTableClear = true;
		clearTable();
	}
	// Play the replay loop.
	if (replayIndex < game.length){
		if (game[replayIndex+1] == 1){
			document.getElementById(game[replayIndex]).style.background = hit;
		} else {
			document.getElementById(game[replayIndex]).style.background = miss;
		}
		replayIndex += 2;
		
		if (replayIndex < game.length){
			setTimeout("replay()", 500);
		}		
	}	
}

// Set selected game data and replay it.
function setReplayGame(game){
	isTableClear = true;
	clearTable();
	replayIndex = 0;
	gameToReplay = localStorage["game" + game];
	latestUserDeploy = localStorage["shipsPlayer" + game];
	replay();
}

// Get game data from localStorage.
function getReplay() {
	var replayGames = new Array();
	for (var i = 0; i < parseInt(localStorage.totalGames); i++) {
		replayGames.push("game" + (i + 1));
	}
	addRowsReplay("replayTabel", replayGames);
	fadeIn("replay");
}

// Add table rows with stored games.
function addRowsReplay(ID, replayArray) {
	var table = document.getElementById(ID);
	for (var i = 0; i < replayArray.length; i++) {
		var row = document.createElement("tr");
		//var name = document.createElement("td");
		var btn = document.createElement("button");
		btn.innerHTML = "Game " + (i + 1);
		btn.setAttribute("onclick", "setReplayGame("+(i+1)+")");
		//row.appendChild(name);
		row.appendChild(btn);
		table.appendChild(row);
	}
}
